<template>
    <div class="white-box">
        <div class="attr-one">
            <p>属性名称：</p>
            <div class="attr-right">
                <el-input class="attr-input" v-model="name" placeholder="请输入属性名称" clearable />
            </div>
        </div>
        <!-- <div class="attr-one">
            <p>商品分类：</p>
            <div class="attr-right">
                <el-select
                    class="attr-input"
                    v-model="class_id"
                    clearable
                    placeholder="输入分类名称"
                    filterable
                    :filter-method="filterClass"
                    @clear="clearCate"
                >
                    <el-option :label="item.title" :value="item.cate_id" v-for="item in cate_arrs" :key="item.title" />
                </el-select>
            </div>
        </div> -->
        <div class="attr-one">
            <p>排序：</p>
            <div class="attr-right">
                <el-input class="attr-input" v-model="sort" placeholder="请输入排序数字" oninput="value=value.replace(/[^\d]/g,'')" clearable />
            </div>
        </div>
        <div class="attr-one">
            <p>属性筛选：</p>
            <div class="attr-right">
                <el-radio-group v-model="attr_radio">
                    <el-radio label="0" size="large">筛选</el-radio>
                    <el-radio label="1" size="large">不筛选</el-radio>
                </el-radio-group>
            </div>
        </div>
        <div class="attr-one" style="align-items: flex-start">
            <p>属性值多选：</p>
            <div class="attr-right">
                <el-checkbox v-model="all_checked" :true-label="1" :false-label="0" style="height: auto; margin-top: 4px">启用</el-checkbox>
                <div class="input-tips">该属性支持选择多个属性值，比如选择鲜花的枝粗、枝长、颜色等等。</div>
            </div>
        </div>
        <div class="attr-one" style="align-items: flex-start">
            <p>属性值必选：</p>
            <div class="attr-right">
                <el-checkbox v-model="must_checked" :true-label="1" :false-label="0" style="height: auto; margin-top: 4px">启用</el-checkbox>
                <div class="input-tips">启用后，该属性为用户下单必选内容。</div>
            </div>
        </div>
        <div class="attr-list__h3">属性值列表</div>
        <div class="attr-add">
            <el-button type="primary" @click="dialogAttr = true">添加属性值</el-button>
        </div>

        <!-- 属性值 -->
        <div class="attr-table" v-loading="loading">
            <div class="attr-th flexs">
                <div class="attr-td attr-th__one">序号</div>
                <div class="attr-td attr-th__two">属性值<span>(长按拖动排序)</span></div>
                <div class="attr-td attr-th__four">操作</div>
            </div>
            <draggable v-model="arr_data" item-key="index" animation="200" v-if="arr_data.length > 0 && !loading">
                <template #item="{ element, index }">
                    <div class="attr-tr flexs">
                        <div class="attr-td attr-th__one">{{ index + 1 }}</div>
                        <div class="attr-td attr-th__two">
                            <el-input v-model.trim="element.title" clearable placeholder="请输入属性值" style="width: 300px" @blur="() => blurInput(element)" />
                        </div>
                        <div class="attr-td attr-th__four">
                            <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(element, index)">
                                <template #reference>
                                    <el-button class="theme-btn" link type="primary">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </div>
                </template>
            </draggable>
            <div class="table-none flexs-center" v-if="arr_data.length == 0 && !loading">暂无数据</div>
        </div>
        <!-- 分页 -->
        <!-- <el-pagination background v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="pageSizeNum"
            :total="totalNums" layout="total, sizes, prev, pager, next, jumper">
        </el-pagination> -->
        <div class="foot-btn flexs-center">
            <el-button type="primary" size="large" :loading="btnLoading" @click="handleConfirm">保存</el-button>
        </div>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogAttr"
            title="添加属性值"
            width="560px"
            :close-on-click-modal="false"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeAttrClass"
        >
            <el-form ref="ruleAttrRef" :model="ruleAttrForm" :rules="ruleCheckAttr" label-width="120px">
                <el-form-item label="属性值名称" prop="name">
                    <el-input v-model.trim="ruleAttrForm.name" clearable placeholder="请输入属性值名称" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitAttrForm(ruleAttrRef)"> 确认添加 </el-button>
                        <el-button @click="resetAttrForm(ruleAttrRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive } from "vue"
import { useRouter, useRoute } from "vue-router"
import draggable from "vuedraggable"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

const loading = ref(false)
const arr_data = ref([])

const eid = route.query.eid || ""
onMounted(() => {
    pubClass()

    eid && getEdit()
})

// 获取编辑信息
function getEdit() {
    loading.value = true
    proxy.$axios
        .get("product/attr/update", {
            params: {
                attr_id: eid,
            },
        })
        .then((res) => {
            loading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                name.value = result.attr_name
                sort.value = result.order_by
                all_checked.value = result.is_multiple
                must_checked.value = result.is_necessary
                // class_id.value = result.cate_id
                attr_radio.value = String(result.type)
                let arrs = []
                for (let i = 0; i < result.attr_value_list.length; i++) {
                    arrs.push({
                        title: result.attr_value_list[i].attr_value_name,
                        attr_value_id: result.attr_value_list[i].attr_value_id,
                    })
                }
                arr_data.value = arrs
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            loading.value = false
        })
}

/**
 * 保存
 * @property {String} name 属性项名称
 * @property {String} sort 属性项排序
 * @property {String} attr_radio 筛选类型
 * @property {Boolean} btnLoading 按钮状态
 * @property {Function} handleConfirm 保存
 */
const name = ref("")
// const class_id = ref("")
const sort = ref("")
const attr_radio = ref("0")
const btnLoading = ref(false)
const all_checked = ref(0) // 是否开启属性多选
const must_checked = ref(0) // 是否开启属性必选
const handleConfirm = () => {
    if (name.value == "") {
        proxy.$message({ message: "请输入属性名称！", type: "warning" })
        return
    }
    if (arr_data.value.length == 0) {
        proxy.$message({ message: "请添加属性值！", type: "warning" })
        return
    }
    if (sort.value == "") {
        proxy.$message({ message: "请输入排序数字！", type: "warning" })
        return
    }
    let index = arr_data.value.findIndex((item) => item.title == "")
    if (index > -1) {
        proxy.$message({ message: "属性值不能为空！", type: "warning" })
        return
    }

    let arrs = []
    arr_data.value.map((item) => {
        arrs.push(item.title)
    })

    let data = {
        title: name.value,
        // cate_id: class_id.value,
        is_multiple: all_checked.value,
        is_necessary: must_checked.value,
        type: attr_radio.value,
        order_by: sort.value,
        attr_value: eid ? arr_data.value : arrs,
    }
    eid && (data.attr_id = eid)
    let url = eid ? "product/attr/update" : "product/attr/add"
    btnLoading.value = true
    proxy.$axios
        .post(url, data)
        .then((res) => {
            btnLoading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "保存成功！", type: "success" })
                router.push("/Goods/GoodsAttr")
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            btnLoading.value = false
        })
}

/**
 * 添加/编辑属性值
 * @property {Boolean} dialogAttr 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Array} ruleAttrRef 表单规则
 * @property {Object} ruleAttrForm  表单字段
 * @property {Object} ruleCheckAttr  表单提示
 * @property {Function} submitClassForm 提交表单
 * @property {Function} closeAttrClass 关闭弹窗
 */
const dialogAttr = ref(false)
const form_loading = ref(false)
const ruleAttrRef = ref(null)
const ruleAttrForm = reactive({
    name: "",
    attr_id: "",
})
const ruleCheckAttr = reactive({
    name: [{ required: true, message: "请输入属性值名称", trigger: "blur" }],
})
const submitAttrForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            let index = arr_data.value.findIndex((item) => item.title === ruleAttrForm.name)
            if (index > -1) {
                proxy.$message({ message: "重复属性值不能添加！", type: "warning" })
                return
            }
            // 编辑时
            if (eid) {
                form_loading.value = true
                proxy.$axios
                    .post("product/attr/value/add", {
                        attr_id: eid,
                        title: ruleAttrForm.name,
                    })
                    .then((res) => {
                        form_loading.value = false
                        if (res.data.code == 0) {
                            dialogAttr.value = false
                            getEdit()
                        } else {
                            proxy.$message({ message: res.data.msg, type: "error" })
                        }
                    })
                    .catch((err) => {
                        form_loading.value = false
                    })
            } else {
                let data = {
                    title: ruleAttrForm.name,
                }
                dialogAttr.value = false
                arr_data.value.push(data)
            }
        }
    })
}
const resetAttrForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeAttrClass = () => {
    dialogAttr.value = false
    resetAttrForm(ruleAttrRef.value)
}

// 删除
const clickDel = (item, index) => {
    if (eid) {
        proxy.$axios
            .post("product/attr/value/delete", {
                attr_value_id: item.attr_value_id,
            })
            .then((res) => {
                if (res.data.code == 0) {
                    arr_data.value.splice(index, 1)
                } else {
                    proxy.$message({ message: res.data.msg, type: "error" })
                }
            })
            .catch((err) => {})
    } else {
        arr_data.value.splice(index, 1)
    }
}

// 编辑时，失去焦点保存属性值
const blurInput = (item) => {
    if (eid) {
        proxy.$axios
            .post("product/attr/value/update", {
                attr_value_id: item.attr_value_id,
                title: item.title,
            })
            .then((res) => {
                if (res.data.code == 0) {
                } else {
                    proxy.$message({ message: res.data.msg, type: "error" })
                }
            })
            .catch((err) => {})
    }
}

/**
 * 获取商品分类、颜色、等级
 * @param {Array} cate_arrs 分类数组
 */
const pub_options = ref({})
const cate_arrs = ref([])
function pubClass() {
    proxy.$axios
        .get("product/search")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                // let arrs = []
                // let lengths = result.cate_list.length < 24 ? result.cate_list.length : 24
                // for (let i = 0; i < lengths; i++) {
                //     arrs.push(result.cate_list[i])
                // }
                pub_options.value = result
                // cate_arrs.value = arrs
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 过滤筛选商品分类
// const filterClass = (val) => {
//     let classs = []
//     pub_options.value.cate_list.forEach((item) => {
//         if (item.title.indexOf(val) > -1) {
//             classs.push(item)
//         }
//     })
//     cate_arrs.value = classs
// }
// 清除分类值事件
// const clearCate = () => {
//     filterClass("")
// }
</script>
<script>
export default {
    name: "GoodsAttrUpdate",
}
</script>

<style lang="less" scoped>
.table-none {
    height: 40px;
    width: 100%;
    color: @gray-6;
}

.attr-table {
    color: @gray-8;
    min-height: 500px;

    .attr-th {
        background: #f5f7fa;
        border-bottom: 1px solid #ebeef5;
    }

    .attr-td {
        padding: 12px 10px;
        overflow: hidden;
    }

    .attr-th__one {
        flex: none;
        width: 120px;
    }

    .attr-th__two {
        flex: 1;

        span {
            color: @gray-7;
            font-size: @font-size-sm;
        }
    }

    .attr-th__three {
        flex: 1;
    }

    .attr-th__four {
        flex: none;
        width: 220px;
    }

    .attr-tr {
        width: 100%;
        border-bottom: 1px solid #ebeef5;
        cursor: move;

        &:hover {
            background: #f5f7fa;
        }
    }
}

.attr-add {
    margin: @margin-md 0px;
}

.attr-list__h3 {
    color: @gray-8;
    font-weight: bold;
    font-size: @font-size-md;
    margin-top: 40px;
    line-height: 40px;
    border-bottom: @border-gray;
}

.attr-one {
    font-size: @font-size-md;
    color: @gray-8;
    display: flex;
    align-items: center;
    margin-bottom: @margin-md;

    p {
        width: 100px;
        text-align: right;
        padding-right: @padding-xs;
    }

    .attr-input {
        width: 260px;
    }
}
</style>
